<template>
    <div>
        <!-- 查询区域 -->
        <div class="card" style="margin-bottom:20px;">
            <el-input style="width:240px; margin-right:10px;" v-model="data.search.title" placeholder="请输入查询标题"
                prefix-icon="Search"></el-input>
            <el-button type="primary" @click="dataLoad">查询</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>
        <!-- 操作区域 -->
        <div class="card" style="margin-bottom:10px;">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleDeleteBatch">批量删除</el-button>
        </div>
        <!-- 数据表区域 -->
        <div class="card" style="margin-bottom:5px;">
            <!-- 数据表 -->
            <el-table :data="data.tableData" stripe @selection-change="handleSelection">
                <el-table-column type="selection" width="55"/>
                <el-table-column label="标题" prop="title" />
                <el-table-column label="封面">
                    <template  #default="scope">
                        <el-image v-if="scope.row.img" :src="scope.row.img" :preview-src-list=[scope.row.img] preview-teleported style="display:block;width:40px;height:40px;border-radius:5px;"/>
                    </template>
                </el-table-column>
                <el-table-column label="简介" prop="description" show-overflow-tooltip="true"/>
                <el-table-column label="内容">
                    <template #default="scope">
                        <el-button type="primary" @click="view(scope.row.content)">查看内容</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" :formatter="dateFormatter">
                    
                </el-table-column>
                
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link type="primary" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button link type="danger" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页插件 -->
            <div style="margin-top:15px;">
                <el-pagination v-model:current-page="data.currentPage" v-model:page-size="data.pageSize"
                    :page-size="[10, 20, 50, 100]" 
                    layout="total,sizes,prev,pager,next,jumper" :total="data.total" @size-change="dataLoad"
                    @current-change="dataLoad" />
            </div>
        </div>
        
        <!-- 新增编辑弹出框 -->
        <el-dialog v-model="data.formVisible" title="文章信息" width="800" destroy-on-close>
            <el-form ref="formRef" :rules="data.rules" :model="data.form" style="margin:20px;" label-width="auto">
                <el-form-item label="封面" style="text-align: center;">
                    <el-upload class="avatar-uploader" 
                        action="http://localhost:8088/files/upload"
                        :show-file-list="false"
                        :on-success="handleImgSuccess"
                        >
                        <img v-if="data.form.img" :src="data.form.img" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="data.form.title" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="简介" prop="description">
                    <el-input type="textarea" :rows="3" v-model="data.form.description" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="内容">
                    <div style="border:1px solid #ccc;">
                        <Toolbar style="border-bottom:1px solid #ccc;" :editor="editorRef" :mode="mode"/>
                        <Editor style="height:500px;overflow-y:hidden;" v-model="data.form.content" :mode="mode" :defaultConfig="editorConfig" @onCreated="handleCreated"/>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.formVisible = false">取消</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 新增编辑弹出框结束 -->
         <!--内容查看框-->
        <el-dialog title="内容" v-model="data.viewVisible" width="50%" :close-on-click-modal="false">
            <div class="editor-content-view" style="padding:20px" v-html="data.form.content"></div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="data.viewVisible=false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
         <!--内容查看框结束-->
    </div>
</template>
<script setup>
import {reactive,onBeforeUnmount,ref,shallowRef} from "vue"
import { Search,Delete,Edit } from '@element-plus/icons-vue'
import request from "@/utils/request"
import { ElMessageBox } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css'
import {Editor,Toolbar} from '@wangeditor/editor-for-vue'
const data = reactive({
    search: {username:null,nickName:null},//绑定查询参数
    tableData: [],
    currentPage: 1,
    pageSize: 10,
    total: 0,
    formVisible:false,
    form:{},
    ids:[],
    viewVisible:false,
    model:'default'
})

const numFormatter=(num)=>{
    if(num<10)return "0"+num
    else return num
}
const dateFormatter = (row,col)=>{

    let currentTime = new Date(row.createTime)
    let year = currentTime.getFullYear()
    let month = numFormatter(currentTime.getMonth()+1)
    let date = numFormatter(currentTime.getDate())
    let hour = numFormatter(currentTime.getHours())
    let minutes = numFormatter(currentTime.getMinutes())
    let second = numFormatter(currentTime.getSeconds())
    return year+"-"+month+"-"+date+" "+hour+":"+minutes+":"+second
}


const formRef = ref()

//数据表数据加载函数
const dataLoad = ()=>{
    request.post("/article/getPage",{pageNum:data.currentPage,pageSize:data.pageSize,sysUser:data.search}).then(res=>{
        if(res.code===0){ //访问接口成功后绑定数据
            data.total = res.data.total
            data.tableData = res.data.list
        }else{
            ElMessage.error(res.message)
        }
        
    })
}
//执行加载数据函数
dataLoad()

//重置查询条件
const reset = ()=>{
    data.search.username = null
    data.search.nickName = null
    dataLoad()
}

//打开新增弹窗
const handleAdd=()=>{
    data.formVisible = true
    data.form={}
}

//打开编辑弹窗，并加载需要编辑数据
const handleEdit=(row)=>{
    data.form = JSON.parse(JSON.stringify(row))//深拷贝一个新的对象用于编辑，不影响现有的
    data.formVisible = true
}

//
const handleDelete=(row)=>{
    ElMessageBox.confirm("确认删除数据？",'删除确认',{type:'warning'}).then(()=>{
        request.delete('/article/deleteById',{
            params:{
                id:row.id
            }
        }).then(res=>{
            if(res.code===0){
                ElMessage.success("操作成功")
                dataLoad()
            }else{
                ElMessage.error(res.message)
            }
        })
    }).catch()
   
}

const save=()=>{
    formRef.value.validate((valid)=>{
        if(valid){
            data.form.id?update():add()
        }
    })
    
   
}
const add = ()=>{
    request.post('/article/save',data.form).then(res=>{
        if(res.code===0){
            data.formVisible=false
            ElMessage.success("操作成功")
            dataLoad()
        }else{
            ElMessage.error(res.message)
        }
    })
}

const update=()=>{
    request.put('/article/update',data.form).then(res=>{
        if(res.code===0){
            data.formVisible=false
            ElMessage.success("操作成功")
            dataLoad()
        }else{
            ElMessage.error(res.message)
        }
    })
}

const handleSelection=(rows)=>{
    console.log(rows)
    data.ids = rows.map(row => row.id)
    
    console.log(data.ids)
}

const handleDeleteBatch=()=>{
    if(data.ids.length===0){
        ElMessage.warning("请选择数据")
        return
    }
    ElMessageBox.confirm("确认删除数据？",'删除确认',{type:'warning'}).then(()=>{
        request.delete('/article/deleteByIds',{data:data.ids}).then(res=>{
            if(res.code===0){
                ElMessage.success('操作成功')
                dataLoad()
            }else{
                ElMessage.error(res.message)
            }
        })
    }).catch()
}

const handleImgSuccess= (res)=>{
    console.log(res.data)
    data.form.img=res.data;
}
/**
 * wangEditor5初始化开始
 */
const baseUrl = "http://localhost:8088"
 const editorRef = shallowRef()
const mode = 'default'
const editorConfig = {MENU_CONF:{}}
//图片上传配置
editorConfig.MENU_CONF['uploadImage']={
    server:baseUrl + '/files/wang/upload',
    fieldName:'file',
}
///组件销毁时，也及时销毁编辑器，否则造成内存泄漏
onBeforeUnmount(()=>{
    const editor = editorRef.value
    if(editor == null) return
    editor.destroy()
})
//记录editor 实例
const handleCreated = (editor)=>{
    editorRef.value = editor
}
const view = (content)=>{
    data.form.content = content
    data.viewVisible = true
}
</script>